package com.kuaikan.cnbeta.srvc;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bsi.app.srvc.BaseSrvc;
import com.kuaikan.cnbeta.pojo.News;
import com.kuaikan.cnbeta.pojo.News;
import com.kuaikan.cnbeta.util.Const;

import android.content.Context;

public class NewsSrvc extends BaseSrvc {

	/**
	 * 单例的实现
	 */
	public static NewsSrvc singleton = null;

	protected NewsSrvc(Context context) {
		super(context);
	}

	public static synchronized NewsSrvc getInstance(Context context) {
		if (singleton == null) {
			singleton = new NewsSrvc(context);
		}
		return singleton;
	}

	final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public static final int PAGE_CNT=20;

	public List<News> getNewsTitles(String url) throws Exception {
		List<News> list = new ArrayList<News>();
		Document doc = Jsoup.connect(url).get();
		Elements divAllNewsList = doc.select("#all_news_list");
		Elements dlList = divAllNewsList.select("dl");
		for (int i = 0; i < dlList.size(); i++) {
			Element dl = dlList.get(i);
			News item = new News();
			Element dtTitle = dl.select("dt a").first();
			String newsUrl = dtTitle.attr("href");
			String newsTitle = dtTitle.text();
			String summary = dl.select("dd div.newsinfo p").text();
			summary=summary.substring(0,summary.length()-6);
			String newsTime = dl.select("div.tools div").text().substring(4);
			String clickCnt = dl.select("ul li.click").text();
			String commentsCnt = dl.select("ul li.comments").text();
			String score = dl.select("ul li.score").text();
			String imgUrl=dl.select("div.pic img").attr("src");
			String newsId=dl.id();
			newsId=newsId.substring(newsId.length()-6);
			item.setNewsId(newsId);
			item.setTitle(newsTitle);
			item.setUrl(new StringBuilder(Const.CN_BETA_URL).append(newsUrl).toString());
			item.setSummary(summary);
			item.setNewsTime(sdf.parse(newsTime));
			item.setClickCnt(Integer.parseInt(clickCnt));
			item.setCommentCnt(Integer.parseInt(commentsCnt));
			item.setScore(Integer.parseInt(score));
			item.setTitleImageUrl(imgUrl);
			
			list.add(item);
			
		}
		return list;
	}
	
	public News getNewsContent(News news)  throws Exception {
		Document doc = Jsoup.connect(news.getUrl()).get();
		String contentHTML=doc.select("section.article_content div.content").html();
		news.setContent(contentHTML);
		news.setUpdateTime(new Date());
		return news;
	}
	
	public void saveNewsList(List<News> list){
		for (News news : list) {
			
			news.setUpdateTime(new Date());
			super.saveOrUpdate(news);
		}
	}
	
	public void updateContent(News news){
		super.update(news);
	}
}
